package io;

import java.io.*;
import java.util.Scanner;

public class ApplicationExampleDemo3 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入要搜索的路径:");
        String rootPath=sc.next();
        File rootFile=new File(rootPath);
        if(!rootFile.isDirectory()) {
            System.out.println("输入的路径有误");
            return;
        }
        System.out.println("请输入要搜索的关键词:");
        String key=sc.next();
        scan(rootFile,key);
    }
    //递归查询文件,查找搜索词
    private static void scan(File curFile,String key) {
        if(!curFile.isDirectory()) {
            return;
        }
        File[] files=curFile.listFiles();
        if(files==null || files.length==0) {
            return;
        }
        for(File file:files) {
            if(file.isFile()) {
                doSearch(file,key);
            }else {
                scan(file,key);
            }
        }
    }
    private static void doSearch(File file,String key) {
        //打开文件,读取文件内容
        StringBuilder sb=new StringBuilder();
        try(Reader reader=new FileReader(file)) {
            char[] buffer=new char[1024];
            while(true) {
                int n=reader.read(buffer);
                if(n==-1) {
                    break;
                }
                String s=new String(buffer,0,n);
                sb.append(s);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
        if(sb.indexOf(key)==-1) {   //次数的indexOf是查找stringBuilder中key对应的下标,若是没有找到,返回-1
            return;
        }
        System.out.println("找到匹配的文件:"+file.getAbsolutePath());
    }
}
